package com.imist.service.impl2;

import com.imist.dao.OrderDao;
import com.imist.dao.ProductDao;
import com.imist.entity.Order;
import com.imist.entity.Product;
import com.imist.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Date;

/**
 * 基于TransactionTemplate
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ProductDao productDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private TransactionTemplate transactionTemplate;


    /**
     * 不需要每次开启事务提交事务，只需要考虑回滚即可
     * @param order
     */
    public void addOrder(final Order order) {
        //设置基本的业务规则
        order.setCreateTime(new Date());
        order.setStatus("待付款");

        transactionTemplate.execute(new TransactionCallback<Object>() {
            public Object doInTransaction(TransactionStatus transactionStatus) {
               try{
                   orderDao.insert(order);
                   Product product = productDao.select(order.getProductsId());
                   //设置库存
                   product.setStock(product.getStock() - order.getNumber());
                   productDao.update(product);
               }catch (Exception e ){
                   e.printStackTrace();
                   transactionStatus.setRollbackOnly();
               }
                //这里不需要返回
                return null;
            }
        });
    }
}
